package com.glsc.ngateway.common.api.common.dto;

import com.github.pagehelper.PageInfo;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @Title: PageDataResult
 * @Description: 封装DTO分页数据（记录数和所有记录）
 * @version: 1.0
 */
public class PageDataResult<T> implements Serializable {

    private Integer code = 0; // 默认结果为18，表示空

    private String msg;
    //总记录数量
    private Integer totals;

    private List<T> list;

    public PageDataResult(PageInfo pageInfo) {
        if(pageInfo.getList().size()!=0){
            this.code = 0;
            this.totals = Math.toIntExact(pageInfo.getTotal());
            this.list = pageInfo.getList();
        }
    }
    public static PageDataResult empty() {
        return new PageDataResult(0, "", new ArrayList<>());
    }

    public PageDataResult() {
    }

    public PageDataResult(Integer pageNum, Integer pageSize, List<T> totalList) {
        Pageable pageable = PageRequest.of(PageUtil.initPageNo(pageNum) - 1, PageUtil.initPageSize(pageSize));
        int start = (int) pageable.getOffset();
        int end = (start + pageable.getPageSize()) > totalList.size() ? totalList.size() : (start + pageable.getPageSize());
        this.code = 0;
        this.msg = "查询分页成功";
        this.totals = totalList.size();
        this.list = totalList.subList(start, end);
    }

    public PageDataResult(int code, String msg, List<T> data) {
        this.code = code;
        this.msg = msg;
        this.list = data;
        this.totals = data.size();
    }

    public static PageDataResult error(String msg) {
        return new PageDataResult(-1, msg, new ArrayList());
    }

    public static <T> PageDataResult success(String msg, List<T> data) {
        return new PageDataResult(0, msg, data);
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Integer getTotals() {
        return totals;
    }

    public void setTotals(Integer totals) {
        this.totals = totals;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    @Override
    public String toString() {
        return "PageDataResult{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", totals=" + totals +
                ", list=" + list +
                '}';
    }
}
